var timeout = 10*1000;
var timeoutKeepAlive = 60*1000;

function keepAlive() {
    http_request = new XMLHttpRequest();
    http_request.open('GET', "/bundle");
    http_request.send(null);
};

function loadApp(){
	sendMessage("App Loaded","The app is loaded and monitoring this page","load");
	verificarResultados();
	setInterval(keepAlive,timeoutKeepAlive);
	setInterval(verificarResultados,timeout);
	
}

function verificarResultados(){
	var els = evaluateXpath("//*[@id=\"update-content-professions-overview-0\"]/span/div/div/ul/li/span/div/div[4]/h6");
	
	for(var i = 0;i<els.length;i++){
		var html = els[i].innerHTML;
		if(html == "Task Complete!"){
			var desc = els[i].parentNode.getElementsByTagName("h4")[0];
			sendMessage(html,desc.innerHTML,"app");
		}
	}
}

function sendMessage(title,msg,type){
		chrome.extension.sendMessage({msg: msg, title: title, type: type }, function(response) { // optional callback - gets response
			console.log(response.returnMsg);
		});
}

function evaluateXpath(STR_XPATH) {
    var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null);
    var xnodes = [];
    var xres;
    while (xres = xresult.iterateNext()) {
        xnodes.push(xres);
    }

    return xnodes;
}

loadApp();